package koutei.stream;

import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDoneException;
import android.content.ContentValues;
import android.content.Context;
import android.widget.Toast;
import android.util.Log;

public class StreamDB{
    public final static String TAG = "SDB";
    public final static int DB_VERSION = 1;
    public final static String DB_NAME = "stream_database"; 
    public final static String BOOKMARK_TABLE = "bookmark";
    public final static String HISTORY_TABLE = "history";
    //Column names
    public final static String NAME = "name";
    public final static String URI = "uri";
    public final static String POS = "pos";
    public final static String TIMESTAMP = "timestamp";
    public final static String TYPE = "type";
    public final static String PREFIX = "koutei.stream.name:";
    public final static int BOOKMARK_TYPE = 1;
    public final static int STATE_TYPE = 0;

    private StreamDBHelper helper;
    private SQLiteDatabase db;
    private Context context;
    private SQLiteStatement getURL;
    private SQLiteStatement getPos;
    private SQLiteStatement uriState;
    private SQLiteStatement posState;
    private SQLiteStatement nameState;
    private SQLiteStatement deleteState;
    private SQLiteStatement deleteBookmark;
    private Cursor viewBookmarksCursor;

    public StreamDB(Context context){
        helper = new StreamDBHelper(context, DB_NAME, null, DB_VERSION);
        db = helper.getWritableDatabase();
        getPos = db.compileStatement("select "+POS+" from "+BOOKMARK_TABLE
            +" where "+NAME+"=?;");
        getURL = db.compileStatement("select "+URI+" from "+BOOKMARK_TABLE
            +" where "+NAME+"=?;");
        deleteBookmark = db.compileStatement("delete from "+BOOKMARK_TABLE
            +" where "+NAME+"=?;");  
        posState = db.compileStatement("select "+POS+" from "+BOOKMARK_TABLE
            +" where "+TYPE+"=?;");
        posState.bindLong(1, STATE_TYPE);
        uriState = db.compileStatement("select "+URI+" from "+BOOKMARK_TABLE
            +" where "+TYPE+"=?;");
        uriState.bindLong(1, STATE_TYPE);
        nameState = db.compileStatement("select "+NAME+" from "+BOOKMARK_TABLE
            +" where "+TYPE+"=?;");
        nameState.bindLong(1, STATE_TYPE);
        deleteState = db.compileStatement("delete from "+BOOKMARK_TABLE
            +" where "+TYPE+"=?;");
        deleteState.bindLong(1, STATE_TYPE);
        this.context = context;
    }

    public boolean saveState(String name, String uri, int pos){
        if(name==null){
            name="";
        }
        Log.v(TAG, "Saving State: type="+STATE_TYPE+" name="+name+
                    " uri="+uri+" pos="+pos);
        ContentValues values = new ContentValues(4);
        values.put(TYPE,STATE_TYPE);
        values.put(NAME, PREFIX+name);
        values.put(URI, uri);
        values.put(POS, new Integer(pos));
        values.put(TIMESTAMP, (new Long(System.currentTimeMillis())));
        try{
            db.insertOrThrow(BOOKMARK_TABLE, null, values);
        }catch(SQLException e){
            Log.v(TAG, "Error: \nFailed to save State: "+ e.toString());
            return false;
        }
        return true;
    }

    public int restorePosState(){
        try{
            return (int) posState.simpleQueryForLong();
        }catch(SQLiteDoneException e ){
            return 0;
        }
    }

    public String restoreNameState(){
        try{
            String tmp = nameState.simpleQueryForString();
            Log.v(TAG, "restoringName "+tmp+" b:"+PREFIX.length()+
                " e:"+tmp.length());
            return tmp.substring(PREFIX.length(), tmp.length());
        }catch(SQLiteDoneException e){
            return null;
        }
    }

    public String restoreUriState(){
        try{
            return uriState.simpleQueryForString();
        }catch(SQLiteDoneException e){
            return null;
        }
    }

    public void deleteState(){
        deleteState.execute();
    }

    public boolean saveBookmark(String name, String uri, int pos){
        ContentValues values = new ContentValues(4);
        values.put(TYPE,BOOKMARK_TYPE);
        values.put(NAME, name);
        values.put(URI, uri);
        values.put(POS, new Integer(pos));
        values.put(TIMESTAMP, new Long(System.currentTimeMillis()));
        try{
            db.insertOrThrow(BOOKMARK_TABLE, null, values);
        }
        catch(SQLException e){
            Log.v(TAG, "Error: \nFailed to save bookmark: "+name);
            return false;
        }
        return true;
    }

    public boolean editBookmark(String oldName, String name, String uri, int pos){
        ContentValues values = new ContentValues(4);
        values.put(NAME, name);
        values.put(URI, uri);
        values.put(POS, new Integer(pos));
        values.put(TIMESTAMP, (new Long(System.currentTimeMillis())));
        String[] whereArgs = {oldName};
        return db.update(BOOKMARK_TABLE, values, NAME+"=?", whereArgs)>0;
    }

    public void removeBookmark(String name){
        deleteBookmark.clearBindings();
        deleteBookmark.bindString(1, name);
        deleteBookmark.execute();
    }

    public String[] viewBookmarks(){
        String[] columnList = {NAME};
        if(viewBookmarksCursor == null){
            viewBookmarksCursor = db.query(BOOKMARK_TABLE, 
                columnList, null, null, null, null, null, null);
        }else{
            viewBookmarksCursor.requery();
        }
        int len = viewBookmarksCursor.getCount();
        String[] names = new String[len];
        for(int i=0; i<len; ++i){
            viewBookmarksCursor.moveToNext();
            names[i] = viewBookmarksCursor.getString(0);
        }
        return names;
    }

    public String getBookmarkUri(String name){
        getURL.clearBindings();
        getURL.bindString(1, name);
        Log.v(TAG,"getting NAME::"+name);
        return getURL.simpleQueryForString();
    }

    public int getBookmarkPos(String name){
        getPos.clearBindings();
        getPos.bindString(1, name);
        return (int) getPos.simpleQueryForLong();
    }

    public void clearHistory(){
        
    }


    public void putHistory(){
        
    }


    public void viewHistory(){
        
    }


    public void getHistory(){
        
    }

    public void close(){
        helper.close();
    }

    public boolean isOpen(){
        return (db!=null||db.isOpen());
    }
}

class StreamDBHelper extends SQLiteOpenHelper{
    private static String MADDOW_URL = "http://msnbcpod.rd.llnwd.net"+
        "/e1/video/podcast/pdv_maddow_netcast_m4v.m4v";
    private static String COUNTDOWN_URL = "http://msnbcpod.rd.llnwd.net"+
        "/e1/video/podcast/pdv_countdown_netcast_m4v.m4v";
    protected final static String BOOKMARK_CREATE = 
        "create table if not exists "+StreamDB.BOOKMARK_TABLE+" ("+
        StreamDB.TYPE+" INTEGER, "+StreamDB.NAME+" TEXT UNIQUE, "+
        StreamDB.URI+" TEXT, "+StreamDB.POS+" INTEGER, "+StreamDB.TIMESTAMP+
        " INTEGER);";
    protected final static String HISTORY_CREATE = 
        "create table if not exists "+StreamDB.HISTORY_TABLE+" ("+StreamDB.TYPE+
        " INTEGER, "+StreamDB.URI+" TEXT UNIQUE, "+StreamDB.POS+" INTEGER, "+
        StreamDB.TIMESTAMP+" INTEGER);";

    public StreamDBHelper(Context context, String name, 
    SQLiteDatabase.CursorFactory factory, int version){
        super(context, name, factory, version);
    }

    public void onCreate(SQLiteDatabase db){
        db.execSQL(BOOKMARK_CREATE);
        //Sample streams
        try{
            Integer zero = new Integer(0);
            Long time = new Long(System.currentTimeMillis());
            ContentValues values = new ContentValues(4);
            values.put(StreamDB.TYPE,StreamDB.BOOKMARK_TYPE);
            values.put(StreamDB.NAME, "Rachel Maddow");
            values.put(StreamDB.URI, MADDOW_URL);
            values.put(StreamDB.POS, zero);
            values.put(StreamDB.TIMESTAMP, time);
            db.insertOrThrow(StreamDB.BOOKMARK_TABLE, null, values);
            values.put(StreamDB.TYPE,StreamDB.BOOKMARK_TYPE);
            values.put(StreamDB.NAME, "Countdown");
            values.put(StreamDB.URI, COUNTDOWN_URL);
            values.put(StreamDB.POS, zero);
            values.put(StreamDB.TIMESTAMP, time);
            db.insertOrThrow(StreamDB.BOOKMARK_TABLE, null, values);
        }catch(SQLException e){
            Log.v(StreamDB.TAG, "Error initializing Bookmark DB...");
        }
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){

    }

}

